package com.zzyl.nursing.service.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.util.IdcardUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.zzyl.common.ai.QianFanInvker;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.vo.HealthReportVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.HealthAssessmentMapper;
import com.zzyl.nursing.domain.HealthAssessment;
import com.zzyl.nursing.service.IHealthAssessmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 健康评估Service业务层处理
 *
 * @author alexis
 * @date 2025-01-06
 */
@Service
public class HealthAssessmentServiceImpl extends ServiceImpl<HealthAssessmentMapper, HealthAssessment> implements IHealthAssessmentService {
    @Autowired
    private HealthAssessmentMapper healthAssessmentMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private QianFanInvker qianFanInvker;

    /**
     * 查询健康评估
     *
     * @param id 健康评估主键
     * @return 健康评估
     */
    @Override
    public HealthAssessment selectHealthAssessmentById(Long id) {
        return healthAssessmentMapper.selectById(id);
    }

    /**
     * 查询健康评估列表
     *
     * @param healthAssessment 健康评估
     * @return 健康评估
     */
    @Override
    public List<HealthAssessment> selectHealthAssessmentList(HealthAssessment healthAssessment) {
        return healthAssessmentMapper.selectHealthAssessmentList(healthAssessment);
    }

    /**
     * 新增健康评估
     *
     * @param healthAssessment 健康评估
     * @return 结果
     */
    @Override
    public Long insertHealthAssessment(HealthAssessment healthAssessment) {
        try (InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("perter/perter.txt");
             InputStreamReader s = new InputStreamReader(resourceAsStream, "UTF-8");
             BufferedReader bf = new BufferedReader(s)) {
            String c = null;
            String healthReport = (String) redisTemplate.opsForHash().get("healthReport", healthAssessment.getIdCard());
            redisTemplate.opsForHash().delete("healthReport", healthAssessment.getIdCard());
            StringBuilder stringBuilder = new StringBuilder();
            while ((c = bf.readLine()) != null) {
                stringBuilder.append(c);
                if (c.contains("体检内容如下")) {
                    stringBuilder.append(healthReport);
                }
            }
            String s1 = qianFanInvker.qianFanInver(stringBuilder.toString());
            HealthReportVo bean = JSONUtil.toBean(s1, HealthReportVo.class);
            healthAssessment.setBirthDate(IdcardUtil.getBirthDate(healthAssessment.getIdCard()).toLocalDateTime());
            healthAssessment.setAge(IdcardUtil.getAgeByIdCard(healthAssessment.getIdCard()));
            healthAssessment.setGender(IdcardUtil.getGenderByIdCard(healthAssessment.getIdCard()));
            double healthIndex = bean.getHealthAssessment().getHealthIndex();
            healthAssessment.setHealthScore(healthIndex + "");
            healthAssessment.setRiskLevel(bean.getHealthAssessment().getRiskLevel());

            if (healthIndex > 100 || healthIndex < 0) {
                throw new BaseException("健康指数不合法");
            } else {
                if (healthIndex < 60) {
                    healthAssessment.setSuggestionForAdmission(1);
                } else {
                    if (healthIndex >= 60 && healthIndex <= 70) {
                        healthAssessment.setNursingLevelName("三级护理");
                    } else if (healthIndex > 70 && healthIndex <= 80) {
                        healthAssessment.setNursingLevelName("二级护理");
                    } else if (healthIndex > 80 && healthIndex <= 90) {
                        healthAssessment.setNursingLevelName("一级护理");
                    } else if (healthIndex > 90) {
                        healthAssessment.setNursingLevelName("特级护理");
                    }
                    healthAssessment.setSuggestionForAdmission(0);
                }
            }

            healthAssessment.setAdmissionStatus(1);
            healthAssessment.setTotalCheckDate(bean.getTotalCheckDate());
            healthAssessment.setAssessmentTime(LocalDateTime.now());
            healthAssessment.setReportSummary(bean.getSummarize());
            healthAssessment.setDiseaseRisk(JSONUtil.toJsonStr(bean.getRiskDistribution()));
            healthAssessment.setAbnormalAnalysis(JSONUtil.toJsonStr(bean.getAbnormalData()));
            healthAssessment.setSystemScore(JSONUtil.toJsonStr(bean.getSystemScore()));
            healthAssessment.setCreateTime(DateUtils.getNowDate());
            healthAssessment.setCreateBy("admin");
            save(healthAssessment);

            return healthAssessment.getId();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 修改健康评估
     *
     * @param healthAssessment 健康评估
     * @return 结果
     */
    @Override
    public int updateHealthAssessment(HealthAssessment healthAssessment) {
        return healthAssessmentMapper.updateById(healthAssessment);
    }

    /**
     * 批量删除健康评估
     *
     * @param ids 需要删除的健康评估主键
     * @return 结果
     */
    @Override
    public int deleteHealthAssessmentByIds(Long[] ids) {
        return healthAssessmentMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除健康评估信息
     *
     * @param id 健康评估主键
     * @return 结果
     */
    @Override
    public int deleteHealthAssessmentById(Long id) {
        return healthAssessmentMapper.deleteById(id);
    }
}
